package com.cml;

import com.cml.handler.ServerDecoderHandler;
import com.cml.handler.ServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;

/**
 * 姓名：陈茂林
 * 时间：2024/4/2
 * 描述：
 */
public class Server implements Lifecycle{
    private ServerBootstrap serverBootstrap;
    EventLoopGroup bossGroup ;
    EventLoopGroup workerGroup;

    private int port;
    private Logger logger = LogManager.getLogger(Server.class);

    public Server(int port){
        this.port = port;
        this.init();
    }
    public void init() {
        EventLoopGroup bossGroup = new NioEventLoopGroup(); // 默认的线程池的大小，cpu core * 2
        EventLoopGroup workerGroup = new NioEventLoopGroup(20);
        serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                .addLast(new ServerDecoderHandler())
                                .addLast(new ServerHandler());
                    }
                })
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);
    }

    public void start() {
        try {
            logger.info("开始启动服务");
            ChannelFuture channelFuture =  serverBootstrap.bind(this.port).sync();
            channelFuture.channel().closeFuture().sync();
            logger.info("服务启动完成");
        } catch (InterruptedException e) {
            logger.error(e);
        }finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public void close() {

    }
}
